// addressPackage/pages/addresslist/addresslist.js
import {ajaxFun} from "../../../utils/ajax"
Page({
  data:{
    list:[],
    checked: true,
    num:""
  },
  onLoad(options){
    console.log(options.num);
    if(options.num){
       this.setData({
           num:options.num
       })
    }

   this.getAddressList();//获取地址列表
  },
  async getAddressList(){
    let result=await ajaxFun("/address","get");
    this.setData({
      list:result.data
    })
  },
 async onChange(e) {
      let index=e.target.dataset.index;
      let item=this.data.list[index];
      console.log(item);
      console.log(e.detail);
    // 需要手动对 checked 状态进行更新
    // this.setData({ checked: detail });
    let result=await ajaxFun("/address","put",{
       ...item,
       defaultFlag:e.detail?1:0
    })
    if(result.resultCode==200){
      // this.setData({ checked: e.detail });
      let newList=this.data.list;
      newList.map(item=>{
        item.defaultFlag=0
      })
      // e.detail?newList[index].defaultFlag=1:0
      newList[index].defaultFlag=e.detail?1:0
      this.setData({
        list:newList
      })
    }
  },
  delFun(e){//删除
 
   let  index=e.target.dataset.index;
   let addressId=this.data.list[index].addressId
    wx.showModal({
      title: '提示',
      content: '您是否要删除该地址',
      complete:async (res) => {
        if (res.confirm) {//确定
          let result=await ajaxFun(`/address/${addressId}`,"DELETE");
          if(result.resultCode==200){
             let newList=this.data.list;
             newList.splice(index,1);
             this.setData({
                 list:newList
             })
          }
        }
      }
    })
  },
  editorBtn(e){
    console.log(e.target.id);
    wx.navigateTo({
      url: `/addressPackage/pages/addressadd/addressadd?id=${e.target.id}`,
    })
  },
  goBackFun(e){
    let index=e.target.dataset.index;
    let obj=this.data.list[index]
     if(this.data.num){
         wx.navigateBack();//
       
        
let pages = getCurrentPages();//当前页面
let prePage = pages[pages.length - 2];//上一个页面
prePage.setData({
  addressDesc:obj
})
// console.log(prePage.data.addressDesc);
     }else{
         console.log("我的--地址列表");
     }
  }
 
})